package com.graduation.mybatis.controller;

import com.graduation.mybatis.bean.*;
import com.graduation.mybatis.service.CoachRecommendationsService;
import com.graduation.mybatis.service.DietPlansService;
import jakarta.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * (DietPlans)表控制层
 *
 * @author makejava
 * @since 2025-04-22 11:57:13
 */
@RestController
@RequestMapping("dietPlans")
public class DietPlansController {
    /**
     * 服务对象
     */
    @Resource
    private DietPlansService dietPlansService;

    @Resource
    private CoachRecommendationsService coachRecommendationsService;
//    /**
//     * 分页查询
//     *
//     * @param dietPlans 筛选条件
//     * @param pageRequest      分页对象
//     * @return 查询结果
//     */
//    @GetMapping
//    public ResponseEntity<Page<DietPlans>> queryByPage(DietPlans dietPlans, PageRequest pageRequest) {
//        return ResponseEntity.ok(this.dietPlansService.queryByPage(dietPlans, pageRequest));
//    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<DietPlans> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.dietPlansService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param dietPlans 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<DietPlans> add(DietPlans dietPlans) {
        return dietPlansService.save(dietPlans) ?
                ResponseEntity.ok(dietPlans) :
                ResponseEntity.internalServerError().build();
    }

    /**
     * 编辑数据
     *
     * @param dietPlans 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<DietPlans> edit(DietPlans dietPlans) {
        return dietPlansService.updateById(dietPlans) ?
                ResponseEntity.ok(dietPlans) :
                ResponseEntity.internalServerError().build();
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.dietPlansService.removeById(id));
    }

    /**
     * 删除计划数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Map<String, Object>> deletePlanFoodById(@PathVariable Integer id) {
        Map<String, Object> response = new HashMap<>();

        if(!dietPlansService.removePlanFoodById(id)){
            response.put("message","计划删除失败");
            response.put("success",false);
        }else {
            response.put("message","食物删除成功");
            response.put("success",true);
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 添加食物到计划中
     */
    @PostMapping("/addFoodToPlan")
    public ResponseEntity<Map<String, Object>> addFoodToPlan(@RequestBody AddFoodRequest request) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 调用服务层方法处理业务逻辑
            PlanFoods planFoods = dietPlansService.addFoodToPlan(request);
            response.put("data", planFoods);
            response.put("message", "食物添加成功");
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("message", "添加失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }

    }

    /**
     * 获取计划摘要
     * @param userId
     * @return
     */
    @GetMapping("/summary/{userId}")
    public ResponseEntity<Map<String, Object>> getPlanSummary(
            @PathVariable Integer userId) {
        NutritionSummary summary = dietPlansService.getPlanSummary(userId);
        if(summary == null)
        {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "用户没有活跃计划或是没有对应计划"
            ));
        }
        // 获取餐次食物数据
        List<DietRecordVO> dietRecords = dietPlansService.getDietRecordsByUserId(userId);
        // 按餐次分组
        Map<Integer, List<DietRecordVO>> foodsByMeal = dietRecords.stream()
                .collect(Collectors.groupingBy(DietRecordVO::getMealType));


        // 构建餐次列表
        List<Map<String, Object>> meals = Arrays.asList(1, 2, 3, 4).stream()
                .map(mealType -> {
                    String mealName = getMealName(mealType); // 根据餐次类型获取餐次名称
                    List<DietRecordVO> records = foodsByMeal.getOrDefault(mealType, Collections.emptyList());

                    // 计算营养汇总
                    double totalCalories = records.stream().mapToDouble(DietRecordVO::getCalories).sum();
                    double totalProtein = records.stream().mapToDouble(DietRecordVO::getProtein).sum();
                    double totalFat = records.stream().mapToDouble(DietRecordVO::getFat).sum();
                    double totalCarbohydrate = records.stream().mapToDouble(DietRecordVO::getCarbohydrate).sum();

                    // 构建食物列表
                    List<Map<String, Object>> selectedFoods = records.stream()
                            .map(record -> {
                                Map<String, Object> foodMap = new HashMap<>();
                                foodMap.put("planId", record.getRecordId());
                                foodMap.put("foodId", record.getFoodId());
                                foodMap.put("name", record.getFoodName());
                                foodMap.put("grams", record.getGrams());
                                foodMap.put("calories", record.getCalories());
                                foodMap.put("protein", record.getProtein());
                                foodMap.put("fat", record.getFat());
                                foodMap.put("carbohydrate", record.getCarbohydrate());
                                foodMap.put("mealType", record.getMealType());
                                return foodMap;
                            })
                            .collect(Collectors.toList());

                    return Map.of(
                            "mealType", mealType,
                            "mealName", mealName,
                            "selectedFoods", selectedFoods,
                            "totalCalories", totalCalories,
                            "totalProtein", totalProtein,
                            "totalFat", totalFat,
                            "totalCarbohydrate", totalCarbohydrate
                    );
                })
                .collect(Collectors.toList());

        Map<String, Object> response = new HashMap<>();
        response.put("data", Map.of(
                "success", true,
                "message", "获取成功",
                "summary", summary,
                "meals", meals
        ));

        return ResponseEntity.ok(response);
    }
    /**
     * 应用教练推荐计划
     * @param userId
     * @param recommendationId
     * @return
     */
    @PostMapping("/apply-recommendation/{userId}/{recommendationId}")
    public ResponseEntity<Map<String, Object>> applyCoachRecommendation(
            @PathVariable Integer userId,
            @PathVariable Long recommendationId) {

        coachRecommendationsService.applyCoachRecommendation(userId, recommendationId);
        Map<String, Object> response = new HashMap<>();
        response.put("data",Map.of(
                "success", true,
                "message", "教练推荐计划应用成功"
        ));
        return ResponseEntity.ok(response);
    }

    private String getMealName(Integer mealType) {
        switch (mealType) {
            case 1:
                return "早餐";
            case 2:
                return "午餐";
            case 3:
                return "晚餐";
            case 4:
                return "加餐";
            default:
                return "未知餐次";
        }
    }

}

